<template>
    <el-card class="box-card">

        <el-dialog :title="modalType == 0 ? '新增用户' : '更新用户'" :visible.sync="dialogVisible" width="30%"
            :before-close="handleClose">

            <!-- 用户表单信息 -->
            <el-form :rules="rules" ref="addUserForm" :model="form" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input placeholder="请输入密码" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="name">
                    <el-input placeholder="请输入您的真实姓名" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone">
                    <el-input placeholder="请输入您的真实姓名" v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="用户权限" prop="type">
                    <el-radio v-model="form.type" :label="0">超级管理员</el-radio>
                    <el-radio v-model="form.type" :label="1">普通用户</el-radio>
                </el-form-item>
                <el-form-item v-if="modalType === 1" label="用户状态" prop="status">
                    <el-switch v-model="form.status" :active-value="0" :inactive-value="1" active-text="正常使用"
                        inactive-text="禁用状态">
                    </el-switch>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="submitCancel">取 消</el-button>
                <el-button type="primary" @click="submitAddUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- class="manage-header" -->
        <div style="margin-bottom: 15px;">
            <el-input placeholder="请输入用户名" style="width: 200px;" v-model="searchUserName"></el-input>
            <el-button type="warning" @click="onSubmit" style="margin-left: 10px;" icon="el-icon-search">查询</el-button>
            <el-button type="warning" @click="clean" style="margin-left: 10px;">清空</el-button>
            <el-button @click="dialogVisible = true" type="primary" style="margin-left: 10px;"
                icon="el-icon-circle-plus-outline">新增用户</el-button>
        </div>
        <div class="common-tabel">
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="id" fixed label="用户id" width="180">
                </el-table-column>
                <el-table-column prop="type" label="权限" width="180">
                    <template slot-scope="scope">
                        <!-- 插入 el-tag -->
                        <el-tag :effect="scope.row.type === 0 ? 'dark' : 'plain'">{{ scope.row.type === 0 ? "超级管理员" : "普通用户"
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="200">
                    <template slot-scope="scope">
                        <el-tag :effect="scope.row.status === 0 ? 'dark' : 'plain'">{{ scope.row.status === 0 ? "正常使用" :
                            "禁用状态" }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" width="180">
                </el-table-column>
                <el-table-column prop="password" label="密码" width="180">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="phone" label="联系方式" width="180">
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="90">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" circle
                            @click="handleEdit(scope.row)"></el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" circle
                            @click="handleDelete(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pager">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageInfo.currentPage" :page-sizes="[6, 12]" :page-size="pageInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
    </el-card>
</template>

<script>
import { getAllUserRequest, addUserRequest, deleteUserRequest, getUserByIdRequest, updateUserRequest, updateUserStatusRequest, getUserByNameRequest } from '@/api/user'

export default {
    name: 'User',
    data() {
        return {
            dialogVisible: false,
            form: {
                username: 'test2',
                password: '66666666',
                name: '赵六',
                phone: '17872587371',
                type: '',
                status: ''
            },
            rules: {
                username: [
                    { required: true, message: "请输入用户名" }
                ],
                password: [
                    { required: true, message: "请输入密码" }
                ],
                name: [
                    { required: true, message: "请输入您的真实姓名" }
                ],
                phone: [
                    { required: true, message: "请输入联系方式" }
                ]
            },
            tableData: [],
            modalType: 0,  // 0表示新增的弹窗，1表示更新的弹窗
            //  分页数据
            pageInfo: {
                currentPage: 1,  //  当前页数
                pageSize: 6,  //  页面显示数量
                total: 0  //  总条目数
            },
            searchUserName: '',  //  用户输入的模糊查询用户名
        };
    },
    methods: {
        //  获取所有用户信息
        getAllUser() {
            //  发送请求
            getAllUserRequest(this.pageInfo.currentPage, this.pageInfo.pageSize).then((res) => {
                if (res.data.code === 20041) {
                    this.tableData = res.data.data.data
                    this.pageInfo.total = res.data.data.total
                } else {
                    this.errorMsg(res.data.data)
                }
            }).catch((err) => {
                this.errorMsg('用户信息加载失败')
            })
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                    this.form = {}
                })
                .catch(_ => { });
        },
        //  提交添加用户表单
        submitAddUser() {
            this.$refs.addUserForm.validate((valid) => {
                if (!valid) {
                    this.errorMsg('必填信息不能为空哦')
                } else {
                    if (this.modalType == 0) {
                        //  对手机号码进行格式校验
                        let reg = /^1[0-9]{10}$/;
                        if (!reg.test(this.form.phone)) {
                            this.$notify.error({
                                title: '错误',
                                message: '手机号码格式不正确，请重新输入'
                            });
                            return;
                        }

                        // 正则表达式，匹配6位数字和字母的组合，并且总长度不大于18位
                        const regex = /^(?=\S*\d)(?=\S*[a-zA-Z])\S{6,18}$/;
                        if (!regex.test(this.form.password)) {
                            this.$notify.error({
                                title: '错误',
                                message: '密码必须为6位数字+字母组合'
                            });
                            return;
                        }

                        //  发送添加用户请求
                        addUserRequest(this.form).then((res) => {
                            if (res.data.code === 20011) {
                                this.successMsg(res.data.data)
                                this.dialogVisible = false
                                this.form = {}
                            } else {
                                this.errorMsg(res.data.data)
                                this.dialogVisible = true
                            }
                        }).catch(() => {
                            this.errorMsg('用户添加失败，请稍后重试')
                        }).finally(() => {
                            this.getAllUser()
                        })
                    }
                    else {
                        //  对手机号码进行格式校验
                        let reg = /^1[0-9]{10}$/;
                        if (!reg.test(this.form.phone)) {
                            this.$notify.error({
                                title: '错误',
                                message: '手机号码格式不正确，请重新输入'
                            });
                            return;
                        }
                        //  发送修改用户请求
                        updateUserRequest(this.form).then((res) => {
                            if (res.data.code === 20031) {
                                this.successMsg(res.data.data)
                            } else {
                                this.errorMsg(res.data.data)
                            }
                        }).catch(() => {
                            this.errorMsg('用户信息更新失败')
                        }).finally(() => {
                            this.form = {}
                            this.getAllUser()
                            this.dialogVisible = false
                        })
                        // console.log(this.from)
                    }
                }
            })
        },
        //  改变用户状态
        handleStatus(val, status) {
            updateUserStatusRequest(val.id, 1).then((res) => {
                if (res.data.code === 20031) {
                    this.successMsg(res.data.data)
                } else {
                    this.errorMsg(res.data.data)
                }
            }).catch(() => { })
                .finally(() => {
                    // this.getAllUser()
                })
        },
        clean() {
            this.searchUserName = ''
            this.getAllUser()
        },
        //  编辑
        handleEdit(val) {
            this.dialogVisible = true
            this.modalType = 1

            //  发送根据id查询用户信息请求
            getUserByIdRequest(val.id).then((res) => {
                if (res.data.code === 20041) {
                    this.form = res.data.data
                }
            }).catch(() => { })
                .finally(() => {
                })
        },
        //  删除
        handleDelete(val) {

            this.$confirm('确认要删除指定用户信息吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //  发送删除用户请求
                console.log('用户id', val.id)
                deleteUserRequest(val.id).then((res) => {
                    if (res.data.code === 20021) {
                        this.successMsg(res.data.data)
                    }
                    else {
                        this.errorMsg(res.data.data)
                    }
                }).catch(() => { })
                    .finally(() => {
                        this.getAllUser()
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //  页面显示数量发生改变事件
        handleSizeChange(val) {
            // console.log('页面显示数量',val)
            this.pageInfo.pageSize = val
            this.getAllUser()
        },
        //  页码发生改变事件
        handleCurrentChange(val) {
            // console.log('页码', val)
            this.pageInfo.currentPage = val
            this.getAllUser()
        },
        onSubmit() {
            if (this.searchUserName != '') {
                getUserByNameRequest(this.searchUserName).then((res) => {
                    if (res.data.code === 20041) {
                        console.log(res.data.data)
                        this.tableData = res.data.data
                    } else {
                        this.errorMsg(res.data.data)
                    }
                }).catch(() => { })
                    .finally(() => { })
            } else {
                this.$notify({
                    title: '温馨提示',
                    message: '请输入需要查询的用户名',
                    type: 'warning'
                });
            }
        },
        submitCancel() {
            this.modalType = 0
            this.form = {}
            this.dialogVisible = false
        },
        //  成功消息
        successMsg(msg) {
            this.$message({
                message: msg,
                type: 'success'
            });
        },
        //  错误消息
        errorMsg(msg) {
            this.$message({
                message: msg,
                type: 'warning'
            });
        },
    },
    mounted() {
        this.getAllUser()
    },
}
</script>

<style lang="less" scoped>
.box-card {
    height: 90%;

    .manage-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .common-tabel {
        position: relative;
        height: (calc(100% - 62px));

        // .pager {
        //     position: absolute;
        //     bottom: 0;
        //     right: 20px;
        // }
    }
}
</style>